package com.cedifie.lendapp.utils.event;

import android.content.Context;

import androidx.annotation.NonNull;

import com.cedifie.lendapp.http.ApiService;
import com.cedifie.lendapp.http.HttpHelper;
import com.cedifie.lendapp.http.IHttpCallback;
import com.cedifie.lendapp.utils.event.room.CedEvent;
import com.cedifie.lendapp.utils.event.room.CedEventDao;
import com.cedifie.lendapp.utils.event.room.CedEventDatabase;
import com.lib.base.utils.log.LogHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2025/5/30 14:15
 * @Annotation： 用户使用埋点收集与上报
 */
public class CedEventManager {

    private static final long DEFAULT_REPORT_INTERVAL = 60 * 60 * 1000; // 默认60分钟上报一次
    private static final long DEFAULT_CLEANUP_INTERVAL = 30 * 60 * 1000; // 默认30分钟清理一次

    private static volatile CedEventManager instance;
    private final CedEventDao eventDao;
    private final ExecutorService ioExecutor;
    private final ScheduledExecutorService scheduler;

    private CedEventManager(Context context) {
        CedEventDatabase db = CedEventDatabase.getCedDatabase(context.getApplicationContext());
        eventDao = db.eventDao();
        ioExecutor = Executors.newSingleThreadExecutor();
        scheduler = Executors.newSingleThreadScheduledExecutor();
        initScheduledTasks();
    }

    public static CedEventManager init(Context context) {
        if (instance == null) {
            synchronized (CedEventManager.class) {
                if (instance == null) {
                    instance = new CedEventManager(context);
                }
            }
        }
        return instance;
    }

    public static CedEventManager getInstance() {
        return instance;
    }

    /**
     * 记录用户行为事件
     * @param eventType 事件类型
     * @param remark 事件备注
     */
    public void insertCedEvent(@NonNull String eventType, @NonNull String remark) {
        LogHelper.d("ced insert eventType: "+eventType+",eventRemark: "+remark);
        ioExecutor.execute(() -> {
            CedEvent event = new CedEvent(eventType, remark, System.currentTimeMillis(), false);
            eventDao.insert(event);
        });
    }

    /**
     * 立即上报未上报的事件
     */
    public void updateCedEventsNow() {
        ioExecutor.execute(() -> {
            List<CedEvent> unreportedEvents = eventDao.getUnsentEvents();
            if (unreportedEvents.isEmpty()) {
                return;
            }
            submitCedEventsToServerAction(unreportedEvents);
        });
    }

    /**
     * 启动定时上报
     * @param interval 上报间隔（毫秒），0表示使用默认间隔
     */
    public void startScheduledReporting(long interval) {
        long reportInterval = interval > 0 ? interval : DEFAULT_REPORT_INTERVAL;
        scheduler.scheduleAtFixedRate(this::updateCedEventsNow,
                reportInterval, reportInterval, TimeUnit.MILLISECONDS);
    }

    /**
     * 清理已上报的事件
     */
    public void cleanupReportedEvents() {
        ioExecutor.execute(eventDao::deleteCedUploadedEvents);
    }

    /**
     * 释放资源
     */
    public void release() {
        scheduler.shutdown();
        ioExecutor.shutdown();
    }

    private void initScheduledTasks() {
        startScheduledReporting(0);
        scheduler.scheduleAtFixedRate(this::cleanupReportedEvents,
                DEFAULT_CLEANUP_INTERVAL, DEFAULT_CLEANUP_INTERVAL, TimeUnit.MILLISECONDS);
    }

    /**
     * 上报所有事件
     * @param events：所有事件列表
     */
    private void submitCedEventsToServerAction(List<CedEvent> events) {
        if (events.isEmpty()){
            return;
        }
        //上报
        JSONObject params = new JSONObject();
        try {
            JSONArray array = new JSONArray();
            for (CedEvent event : events){
                LogHelper.e("track event >>> id="+event.getId()+">>>type="+event.getType()+">>>remark="+event.getRemark()+">>>timestamp="+event.getTimestamp()+">>>isUpload="+event.isUpload());
                JSONObject obj = new JSONObject();
                obj.put("id",event.getId());
                obj.put("type",event.getType());
                obj.put("remark",event.getRemark());
                obj.put("timestamp",event.getTimestamp());
                array.put(obj);
            }
            params.put("list",array);
            params.put("path",ApiService.API_PATH.CED_API_TRACK_EVENT_BATCH_PATH);
        } catch (JSONException e) {
            LogHelper.e("track params format failed!");
        }
        String httpUrl = ApiService.INSTANCE.getHttpUrl(ApiService.API_URL.CED_API_COMMON_URL);
        HttpHelper.INSTANCE.postCedAction(httpUrl, params, new IHttpCallback() {
            @Override
            public void onRequestSuccess(@NonNull JSONObject data) {
                int code = data.optInt("code");
                if (code == 0){
                    //更新事件状态为已上报
                    setEventsAsUploaded(events);
                } else {
                    LogHelper.e("track update failed!");
                }
            }
            @Override
            public void onRequestError(@NonNull JSONObject error) {
            }
            @Override
            public void onRequestFinish() {
            }
        });
    }

    /**
     * 更新事件状态
     * @param events：所有事件列表
     */
    private void setEventsAsUploaded(List<CedEvent> events) {
        ioExecutor.execute(() -> {
            for (CedEvent event : events) {
                event.setUpload(true);
            }
            eventDao.updateCedEvents(events);
            eventDao.deleteCedUploadedEvents();
        });
    }
}
